//
//  PostImageCell.m
//  com.yjwh.yj
//
//  Created by ferver7 on 2018/10/10.
//  Copyright © 2018年 ferver7. All rights reserved.
//

#import "PostImageCell.h"
#import "PostItemNormalCCell.h"
#import "PostItemAddCCell.h"
#import "PostItemShowCCell.h"
#import "ACMediaManager.h"
#import "ACMediaModel.h"

@interface PostImageCell()<AxcCollectionViewRearrangeDelegate,AxcPhotoBrowserDelegate>
@property (nonatomic, copy) PostImageCellHeightBlock block;
@property (nonatomic, copy) PostSelectMediaBackBlock backBlock;
@property (nonatomic, copy) PostExchangeImagesPoszition exBlock;
@property (nonatomic, copy) PostImageDelBlock delBlock;
@end
@implementation PostImageCell
 
-(void)setPostUrlArr:(NSMutableArray *)postUrlArr
{
    _postUrlArr = postUrlArr;
    NSMutableArray *models = [NSMutableArray array];
    for (NSDictionary *infoDic in postUrlArr) {
        NSString * urlStr;
        if (infoDic[@"url"]) {
            urlStr = infoDic[@"url"];
        }else{
            urlStr = infoDic[@"picPath"];
        }
        NSString *key = [[Axc_WebimageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:urlStr]];
//        NSData *imageData = [Axc_WebimageCache AxcUI_webimageCacheGetDataWithwebKey:key];
//        UIImage *lastPreviousCachedImage = [UIImage imageWithData:imageData];
        UIImage *lastPreviousCachedImage = [[coreAxc_ImageCache_remakes sharedImageCache] imageFromDiskCacheForKey:key];
        ACMediaModel *model = [[ACMediaModel alloc] init];
        model.name = @"url";
        model.uploadType = nil;
        model.image = lastPreviousCachedImage;
        [self.mediaArray addObject:model];
        [self.postImageArr addObject:model];
        [models addObject:model];
    }
    [self layoutCollection:models];
}
-(void)setPostFailImageArr:(NSMutableArray *)postFailImageArr
{
    _postFailImageArr = postFailImageArr;
    [self.mediaArray removeObjectsInArray:postFailImageArr];
    [self layoutCollection:@[]];
}
- (void)awakeFromNib {
    [super awakeFromNib];
    self.contentMargin = 20;
    self.contentPadding = 20;
    self.itemSpace = 5;
    
    self.postCell_State = PostImageCell_State_Normal;
    self.mediaArray = [[NSMutableArray alloc]init];
    self.postImageArr = [[NSMutableArray alloc]init];
    self.selfCollectionView.axcUI_rearrangeDelegate = self;// 设置排序代理
    self.selfCollectionView.axcUI_enableRearrangement = YES; // 是否允许排序
    self.selfCollectionView.axcUI_autoScrollSpeed = 3; // 长按cell接触边缘时collectionView自动滚动的速率，每1/60秒移动的距离
    self.selfCollectionView.axcUI_longPressMagnificationFactor = 1.3; // 长按放大倍数  默认为1.2
}
- (void)observeViewHeight:(PostImageCellHeightBlock)value {
    _block = value;
}

- (void)observeSelectedMediaArray: (PostSelectMediaBackBlock)backBlock {
    _backBlock = backBlock;
}
- (void)observePostExchangeImagesPoszition: (PostExchangeImagesPoszition)exBlock
{
    _exBlock = exBlock;
}
- (void)observeImageDelBlock: (PostImageDelBlock)delBlock
{
    _delBlock = delBlock;
}
+ (CGFloat)defaultCellHeight {
    return (mScreenWidth-120)/3+20;
}
-(void)setPostCell_State:(PostImageCell_State)postCell_State
{
    _postCell_State = postCell_State;
    [self.selfCollectionView reloadData];
}
#pragma mark uicollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    switch (self.postCell_State) {
        case PostImageCell_State_Normal:return 1;
            break;
        case PostImageCell_State_Adding:return self.mediaArray.count + 1;
            break;
        case PostImageCell_State_FullAdd:return self.mediaArray.count;
            break;
        default:
            break;
    }
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.postCell_State) {
        case PostImageCell_State_Normal:{
            PostItemNormalCCell * itemCell = mGetCollectionViewCell(@"postItemNormalCCell", indexPath);
            return itemCell;
        }
            break;
        case PostImageCell_State_Adding:{
            if (indexPath.row == self.mediaArray.count) {
                PostItemAddCCell * itemCell = mGetCollectionViewCell(@"postItemAddCCell", indexPath);
                return itemCell;
            }else{
                PostItemShowCCell * itemCell = mGetCollectionViewCell(@"postItemShowCCell", indexPath);
                
                if (self.boolChangeIndex > 0 && self.boolChangeIndex >=indexPath.row+1) {
                    itemCell.delBtn.hidden = YES;
                    itemCell.delIcon.hidden = YES;
                }
                ACMediaModel *model = [[ACMediaModel alloc] init];
                model = _mediaArray[indexPath.row];
                itemCell.iconImage.image = model.image;
                WS(weakSelf);
                itemCell.ACMediaClickDeleteButton = ^{
                    
                    weakSelf.delBlock(indexPath.row);
                    [weakSelf.mediaArray removeObjectAtIndex:indexPath.row];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self layoutCollection:@[]];
                    });
                };
                return itemCell;
            }
        }
            break;
        case PostImageCell_State_FullAdd:{
            PostItemShowCCell * itemCell = mGetCollectionViewCell(@"postItemShowCCell", indexPath);
            if (self.boolChangeIndex > 0 && self.boolChangeIndex >=indexPath.row+1) {
                itemCell.delBtn.hidden = YES;
                itemCell.delIcon.hidden = YES;
            }
            WS(weakSelf);
            itemCell.ACMediaClickDeleteButton = ^{
                
                weakSelf.delBlock(indexPath.row);
                [weakSelf.mediaArray removeObjectAtIndex:indexPath.row];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self layoutCollection:@[]];
                });
            };
            ACMediaModel *model = [[ACMediaModel alloc] init];
            model = _mediaArray[indexPath.row];
            itemCell.iconImage.image = model.image;
            return itemCell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (self.postCell_State) {
        case PostImageCell_State_Normal: return CGSizeMake(mScreenWidth-2*(self.contentMargin+self.contentPadding)-1, self.frame.size.height-self.contentPadding-1);
            break;
        case PostImageCell_State_Adding: return CGSizeMake((mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3-1, (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3-1);
            break;
        case PostImageCell_State_FullAdd: return CGSizeMake((mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3-1, (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3-1);
            break;
        default:
            break;
    }
    return CGSizeMake(mScreenWidth-80, (mScreenWidth-120)/3);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.postCell_State) {
        case PostImageCell_State_Normal: {
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxSelImages - _mediaArray.count delegate:self];
            ///是否 在相册中显示拍照按钮
            imagePickerVc.allowTakePicture = YES;
            ///是否可以选择显示原图
            imagePickerVc.allowPickingOriginalPhoto = NO;
            ///是否 在相册中可以选择视频
            imagePickerVc.allowPickingVideo = NO;
            [self.rootVC presentViewController:imagePickerVc animated:YES completion:nil];
        };
            break;
        case PostImageCell_State_Adding:{
            if (indexPath.row == self.mediaArray.count) {
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxSelImages - _mediaArray.count delegate:self];
                ///是否 在相册中显示拍照按钮
                imagePickerVc.allowTakePicture = YES;
                ///是否可以选择显示原图
                imagePickerVc.allowPickingOriginalPhoto = NO;
                ///是否 在相册中可以选择视频
                imagePickerVc.allowPickingVideo = NO;
                [self.rootVC presentViewController:imagePickerVc animated:YES completion:nil];
            }else{
//                PostItemShowCCell *cell = mGetCollectionViewCell(@"postItemShowCCell", indexPath);
                
                // 使用初始化和重写SET方法，设置即可调用，无先后顺序，设置即可动态调整  ************************************************
                AxcUI_PhotoBrowser *browser = [[AxcUI_PhotoBrowser alloc] init];
                browser.axcUI_sourceImagesContainerView = self.rootVC.view;                        // 设置父视图
                browser.axcUI_imageCount = self.mediaArray.count;                            // 设置图片总数
                browser.axcUI_currentImageIndex = (int )indexPath.row;                      // 设置当前索引
                browser.axcUI_photoBrowserDelegate = self;                                  // 设置代理回调
                browser.axcUI_convertRectView = self;                                       // 设置扩展动画/放大效果的View
                browser.axcUI_progressSize = CGSizeMake(1, 1);                            // 设置加载指示器大小
//                browser.axcUI_progressViewStyle = self.progressSegmented.selectedSegmentIndex;    // 设置加载指示器风格
//                browser.axcUI_pageTypeMode = AxcPhotoBrowserPageControlStyleNumPage;                                // 设置索引展示模式
                browser.axcUI_saveType = AxcPhotoBrowserStyleLongTapSave;                     // 设置互动模式：按钮保存/长摁保存
                // 如果带有高度适配参数则需要调整适应
                browser.axcUI_automaticallyAdjustsScrollViewInsets = self.rootVC.automaticallyAdjustsScrollViewInsets;
                [browser AxcUI_show];
            }
        };
            break;
        case PostImageCell_State_FullAdd: {
//            PostItemShowCCell *cell = mGetCollectionViewCell(@"postItemShowCCell", indexPath);
            
            // 使用初始化和重写SET方法，设置即可调用，无先后顺序，设置即可动态调整  ************************************************
            AxcUI_PhotoBrowser *browser = [[AxcUI_PhotoBrowser alloc] init];
            browser.axcUI_sourceImagesContainerView = self.rootVC.view;                        // 设置父视图
            browser.axcUI_imageCount = self.mediaArray.count;                            // 设置图片总数
            browser.axcUI_currentImageIndex = (int )indexPath.row;                      // 设置当前索引
            browser.axcUI_photoBrowserDelegate = self;                                  // 设置代理回调
            browser.axcUI_convertRectView = self;                                       // 设置扩展动画/放大效果的View
            browser.axcUI_progressSize = CGSizeMake(1, 1);                            // 设置加载指示器大小
            //                browser.axcUI_progressViewStyle = self.progressSegmented.selectedSegmentIndex;    // 设置加载指示器风格
//            browser.axcUI_pageTypeMode = AxcPhotoBrowserPageControlStyleNumPage;                                // 设置索引展示模式
            browser.axcUI_saveType = AxcPhotoBrowserStyleLongTapSave;                     // 设置互动模式：按钮保存/长摁保存
            // 如果带有高度适配参数则需要调整适应
            browser.axcUI_automaticallyAdjustsScrollViewInsets = self.rootVC.automaticallyAdjustsScrollViewInsets;
            [browser AxcUI_show];
        };
            break;
        default:
            break;
    }
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return self.itemSpace;
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return self.itemSpace;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, self.contentPadding, 10, self.contentPadding);
}
#pragma mark - 排序代理委托

- (BOOL)AxcUI_collectionView:(UICollectionView *)collectionView shouldMoveCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    
    //    NSLog(@"开始位置:%ld", indexPath.row);
    return YES;
}

- (void)AxcUI_collectionView:(UICollectionView *)collectionView putDownCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // 最终停留在的
    //    NSLog(@"最终到:%ld",  indexPath.row);
}

- (BOOL)AxcUI_collectionView:(UICollectionView *)collectionView shouldMoveCell:(UICollectionViewCell *)cell fromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    
    //    NSLog(@"从:%ld, 到x:%ld", fromIndexPath.row, toIndexPath.row);
    if (fromIndexPath.row+1<=self.boolChangeIndex || toIndexPath.row+1<=self.boolChangeIndex) {
        return NO;
    }
    if (self.postCell_State == PostImageCell_State_Adding) {
        if (fromIndexPath.row == self.mediaArray.count || toIndexPath.row == self.mediaArray.count) {
            return NO;
        }
    }
    return YES;
}

- (void)AxcUI_collectionView:(UICollectionView *)collectionView didMoveCell:(UICollectionViewCell *)cell fromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    // 途径的位置
    self.exBlock(fromIndexPath.row, toIndexPath.row);
    
    ACMediaModel * infoDic = self.mediaArray[fromIndexPath.row];
    [self.mediaArray removeObject:infoDic];
    [self.mediaArray insertObject:infoDic atIndex:toIndexPath.row];
//    [self.mediaArray exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
    NSLog(@"从:%ld, 到x:%ld", (long)fromIndexPath.row, (long)toIndexPath.row);
}

#pragma mark - AxcUI_photoBrowser 代理区
- (void)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser
              saveTypeMode:(AxcPhotoBrowserSaveStyle)saveTypeMode
                     Image:(UIImage *)saveImage{
    // 当图片发生互动（长摁/按钮）保存时发生的回调。saveTypeMode根据之前设定的互动模式来反馈相应的操作
    if (saveTypeMode == AxcPhotoBrowserStyleLongTapSave) {
        NSLog(@"长摁");
    }else{
        NSLog(@"按钮");
    }
}
- (UIImage *)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    // 返回当前索引的placeholderImage，这里使用小图加载的缓存作为占位
//    return [Axc_WebimageCache AxcUI_getAxcImageWithCacheKey:self.dataArray[index]];
    ACMediaModel *model = [[ACMediaModel alloc] init];
    model = [_mediaArray objectAtIndexVerify:index];
    return model.image;
}
//- (NSURL *)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
//    // 返回当前索引的高清图
////    NSString *HDurlStr = [self.dataArray[index] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
//    // 替换关键字来实现高清/动图的加载
//    return nil;
//}

#pragma mark - TZImagePickerController Delegate
//处理从相册单选或多选的照片
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSMutableArray *models = [NSMutableArray array];
    for (NSInteger index = 0; index < assets.count; index++) {
        PHAsset *asset = assets[index];
        [ACMediaManager getMediaInfoFromAsset:asset completion:^(NSString *name, id pathData) {
            ACMediaModel *model = [[ACMediaModel alloc] init];
            model.name = name;
            model.uploadType = pathData;
            model.image = photos[index];
            [models addObject:model];
            if (index == assets.count - 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.mediaArray addObjectsFromArray:models];
                    NSMutableArray * postArr = [[NSMutableArray alloc]init];
                    [postArr addObjectsFromArray:self.mediaArray];
                    [postArr removeObjectsInArray:self.postImageArr];
                    self.backBlock(postArr);
                    [self layoutCollection:models];
                });
            }
        }];
    }
   
}
///选取视频后的回调
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    [ACMediaManager getMediaInfoFromAsset:asset completion:^(NSString *name, id pathData) {
        ACMediaModel *model = [[ACMediaModel alloc] init];
        model.name = name;
        model.uploadType = pathData;
        model.image = coverImage;
        model.isVideo = YES;
        model.asset = asset;
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.mediaArray addObjectsFromArray:models];
//            self.backBlock(self.mediaArray);
            [self layoutCollection:@[model]];
        });
    }];
}
///添加选中的image，然后重新布局collectionview
- (void)layoutCollection:(NSArray *)images {
    
    if (self.mediaArray.count == self.maxSelImages) {
        _postCell_State = PostImageCell_State_FullAdd;
    }else if (self.mediaArray.count == 0){
        _postCell_State = PostImageCell_State_Normal;
    }else{
        _postCell_State = PostImageCell_State_Adding;
    }
    CGFloat maxHeight;
    switch (self.postCell_State) {
        case PostImageCell_State_Normal:{
            maxHeight = 125;
        };
            break;
        case PostImageCell_State_Adding:{
            if ((self.mediaArray.count+1)%3 == 0) {
                maxHeight = (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3 * ((self.mediaArray.count+1)/3)+((self.mediaArray.count+1)/3-1)*self.itemSpace+20;
            }else{
                maxHeight = (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3 * ((self.mediaArray.count+1)/3+1)+((self.mediaArray.count+1)/3)*self.itemSpace+20;
            }
        };
            break;
        case PostImageCell_State_FullAdd:{
            if (self.maxSelImages%3 == 0) {
                 maxHeight = (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3 * (self.maxSelImages/3)+(self.maxSelImages/3-1)*self.itemSpace+20;
            }else{
                 maxHeight = (mScreenWidth-2*(self.contentMargin+self.contentPadding+self.itemSpace))/3 * (self.maxSelImages/3+1)+(self.maxSelImages/3)*self.itemSpace+20;
            }
        };
            break;
        default:
            break;
    }
//    NSInteger maxRow = (allImageCount - 1) / 4 + 1;
//    _collectionView.height = maxRow * ACMedia_ScreenWidth/4;
//    self.height = _collectionView.height;
//    //block回调
    !_block ?  : _block(maxHeight);
    [self.selfCollectionView reloadData];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
